<?php
/**
 * odbc简单链接类.
 * 
 * @author 莫 念  
 * @version 1.0
 * @package main
 */

class odbc  {
	
	private $conn = null;
	private $rs = null;
	private $numRows = 0;

	public function __construct($config = array()) {
		if(!$config){
			 exit('请配置数据库');
		}
		$this->conn = @odbc_connect($config["db_dsn"],$config["db_user"],$config["db_pwd"]) or die('sybase not connect');
	}
	public function __destruct() {
		$this->close();
	}

	/**
     * 释放查询结果
     * @access public
     */
    private function free() {
        odbc_free_result($this->rs);
        $this->rs = null;
    }
	
	/**
     * 关闭数据库
     * @access public
     */
    private function close() {
        if ($this->conn){
            odbc_close($this->conn);
        }
        $this->conn = null;
    }

	private function query($sql){
		if(!$sql){
			return ;
		}
		$this->rs = odbc_exec($this->conn,$sql);
		 if (!$this->rs) {
            return false;
        }
		$this->numRows = odbc_fetch_row($this->rs);
			
	}

	public function execute($sql){
		if(!$sql){
			return ;
		}
		$this->query($sql);
		if(!$this->rs){
			return false;
		}
		return true;
	}

	 /**
     * 获得所有的查询数据
     * @access private
     * @return array
     */
    public function getAll($sql) {
		if(!$sql){
			return ;
		}
        //返回数据集
		$this->query($sql);
        $result = array();
	
        if($this->numRows) {
            if(!function_exists("odbc_fetch_array"))
            {
                function odbc_fetch_array($res)
                {
                    if(!odbc_fetch_row($res)) return false;
            
                    $row=array();
                    $numfields=odbc_num_fields($res);
                    for($i=1; $i<=$numfields; $i++)
                    {
                        $row[odbc_field_name($res,$i)]=$row[$i-1]=odbc_result($res,$i);
            
                    }
                    return $row;
                }
            }
                
            while($row = odbc_fetch_array($this->rs))
                $result[]   =   $row;
        }
		
        return $result;
    }

}


$odbc = new odbc(array('db' => 'sa','db_pwd' => '','db_dsn' => 'Driver={SQL Server};Server=127.0.0.1\SQL2005;Database=app;'));
//添加/修改
$sql = "insert into test values('11')";
var_dump($odbc->execute($sql));

//查询
$sql = "select * from test";
var_dump($odbc->getAll($sql));
$odbc->close();